<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入表ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别" prop="comnDictRecentlyUsed">
        <el-select v-model="queryParams.comnDictRecentlyUsed" placeholder="请选择类别" clearable size="small">
          <el-option
            v-for="dict in dict.type.comn_dict_recently_used"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="docNote">
        <el-input
          v-model="queryParams.docNote"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>

      </el-form-item>
      <el-form-item>

        <el-dropdown split-button size="mini" @click="resetQuery" @command="handleCommand">
          重置
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="setting = true">
              <span>---- 最近使用的查询条件 ---- </span>
            </el-dropdown-item>
            <el-dropdown-item v-for="(item,index) in recentlyUsed_queryParameters"
                              v-text = "item.createTime + ' : ' + item.contentJson"
                              :command="item"
            ></el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['comn:recentlyUsed:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['comn:recentlyUsed:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['comn:recentlyUsed:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['comn:recentlyUsed:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recentlyUsedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="时间" align="center" prop="createTime" />
      <el-table-column label="表ID" align="center" prop="userId" />
      <el-table-column label="类别" align="center" prop="comnDictRecentlyUsed">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.comn_dict_recently_used" :value="scope.row.comnDictRecentlyUsed"/>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center" prop="contentJson" />
      <el-table-column label="备注" align="center" prop="docNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['comn:recentlyUsed:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['comn:recentlyUsed:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改最近使用内容对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入表ID" />
        </el-form-item>
        <el-form-item label="类别" prop="comnDictRecentlyUsed">
          <el-select v-model="form.comnDictRecentlyUsed" placeholder="请选择类别">
            <el-option
              v-for="dict in dict.type.comn_dict_recently_used"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="contentJson">
          <el-input v-model="form.contentJson" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="docNote">
          <el-input v-model="form.docNote" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecentlyUsed, getRecentlyUsed, delRecentlyUsed, addRecentlyUsed, updateRecentlyUsed } from "@/api/comn/recentlyUsed";

import { sleepFunc } from '@/utils/date-time'

export default {
  name: "RecentlyUsed",
  dicts: ['comn_dict_recently_used'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 最近使用内容表格数据
      recentlyUsedList: [],
      recentlyUsed_queryParameters: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 备注时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        comnDictRecentlyUsed: null,
        contentJson: null,
        docNote: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "表ID不能为空", trigger: "blur" }
        ],
        comnDictRecentlyUsed: [
          { required: true, message: "类别不能为空", trigger: "change" }
        ],
        contentJson: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getRecentlyUsed_list();
  },
  methods: {

    // 查询条件中的 split button 的下拉内容
    getRecentlyUsed_list(){

      let parameters = {
        'userId':'1',
        'comnDictRecentlyUsed':'query_parameters_recently_used',
        'pageNum':1,
        'pageSize':10,
      }

      listRecentlyUsed(parameters).then(response => {
        this.recentlyUsed_queryParameters = response.rows;
        console.log(response.rows)
      });

    },

    /** 查询最近使用内容列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }

      listRecentlyUsed(this.queryParams).then(response => {
        let thiz = this
        sleepFunc(function(){
          thiz.recentlyUsedList = response.rows;
          thiz.total = response.total;
          thiz.loading = false;
      }, 600)})


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        usedUuid: null,
        userId: null,
        comnDictRecentlyUsed: null,
        contentJson: null,
        docNote: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();

      if( !this.queryParams.comnDictRecentlyUsed && !this.queryParams.docNote) return

      let p = {
        'contentJson': JSON.stringify({
          '参数':`类型：${this.selectDictLabel(this.dict.type.comn_dict_recently_used,
            this.queryParams.comnDictRecentlyUsed)}，备注：${this.queryParams.docNote}`,
          'comnDictRecentlyUsed': this.queryParams.comnDictRecentlyUsed,
          'docNote': this.queryParams.docNote
        }),
        'comnDictRecentlyUsed': 'query_parameters_recently_used',
        'userId': 1,
      }

      addRecentlyUsed(p).then(response => {
        this.getRecentlyUsed_list()
      });

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.usedUuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加最近使用内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const usedUuid = row.usedUuid || this.ids
      getRecentlyUsed(usedUuid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改最近使用内容";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.usedUuid != null) {
            updateRecentlyUsed(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecentlyUsed(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const usedUuids = row.usedUuid || this.ids;
      this.$modal.confirm('是否确认删除最近使用内容编号为"' + usedUuids + '"的数据项？').then(function() {
        return delRecentlyUsed(usedUuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('comn/recentlyUsed/export', {
        ...this.queryParams
      }, `comn_recentlyUsed.xlsx`)
    },

    handleCommand(command) {
      console.log(command)
      let j = JSON.parse(command.contentJson)
      j.pageNum = this.queryParams.pageNum
      j.pageSize = this.queryParams.pageSize
      this.queryParams = j
      this.handleQuery()
    },


  }
};
</script>
